package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_SHOPTUPE_TTL;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Result queryWithList() {
        //1、建一个存放的容器
        List<ShopType> typeList = new ArrayList<ShopType>();

        //2、从redis中获取销售列表
        List<String> stringList = stringRedisTemplate.opsForList().range(CACHE_SHOPTYPE_KEY, 0, -1);

        //3、判断是否从redis中查到数据
        if(stringList.size() != 0){
            //从redis中查到
            //4、将string蕾西转为bean对象
            for (String shopType : stringList){
                ShopType shopType1 = JSONUtil.toBean(shopType, ShopType.class);
                typeList.add(shopType1);
            }
            return Result.ok(typeList);
        }

        //5、没从redis中查到，则从数据库中查找
        typeList = query().orderByAsc("sort").list();
        //6、判断是否查找到
        if (typeList == null){
            //7、没有查到
            return Result.fail("没有查到该列表");
        }
        //8、查到后存入redis
//        stringRedisTemplate.opsForList().leftPushAll(CACHE_SHOPTYPE_KEY,JSONUtil.toJsonStr(typeList));
        for (ShopType shopType : typeList){
            String s1 = JSONUtil.toJsonStr(shopType);
            stringRedisTemplate.opsForList().rightPush(CACHE_SHOPTYPE_KEY,s1);
        }
        stringRedisTemplate.expire(CACHE_SHOPTYPE_KEY,LOGIN_SHOPTUPE_TTL,TimeUnit.MINUTES);

        //9、返回结果
        return Result.ok(typeList);
    }
}
